<?php


namespace App\Http\Admin\Controllers\V1\AdminUser;


use App\Http\Admin\Controllers\V1\BasisController;
use App\Libs\Common\Cache\PermissionMenu;
use App\Models\AdminGroup;
use App\Models\AdminUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class IndexController extends BasisController
{
    protected $modelAdminUser;

    public function __construct()
    {
        parent::__construct();
        $this->modelAdminUser = new AdminUser();
    }

    public function lists()
    {
        $conditions = [
            'not_admin' => 1,
            'keyword' => request('keyword'),
            'username' => request('username'),
            'status' => request('status'),
            'is_super' => request('is_super'),
            'start_time' => request('start_time'),
            'end_time' => request('end_time'),
        ];
        $page = request('page', 1);
        $pageSize = request('page_size', 20);
        $orderArr = [];
        $lists = $this->modelAdminUser->paginateLists($conditions, [], $orderArr, $page, $pageSize);
        $modelAdminGroup = new AdminGroup();

        foreach ($lists as $key=>$val){
            $group = $modelAdminGroup->groupAccess($val->id);
            $lists[$key]->group = $group;
            $lists[$key]->group_str = implode(',',$group);
            $lists[$key]->login_token = adminLoginToken($val->username);
        }
        $statusArray = $this->modelAdminUser->statusArray();
        $isSuperArray = $this->modelAdminUser->isSuperArray();
        return $this->view(compact(array('lists', 'statusArray', 'isSuperArray')), 'admin_user/index/lists');
    }

    public function create()
    {
        if (request()->isMethod('post')) {
            $insertData = [
                'username' => trim(request('username')),
                'password' => trim(request('password')),
                'email' => trim(request('email')),
                'mobile' => trim(request('mobile')),
                'realname' => trim(request('realname')),
                'head_portrait' => trim(request('head_portrait')),
                'introduction' => trim(request('introduction')),
                'is_super' => trim(request('is_super')),
            ];
            $groupStr = request('group_str');
            if(empty($groupStr)){
                return $this->responseMsg('210010',false, '请勾选角色权限');
            }
            $groupArray = explode(',',$groupStr);
            if (!preg_match("/^[A-Za-z]{1}[A-Za-z0-9_-]{2,20}$/", $insertData['username'])){
                return $this->responseMsg('210020',false, '名称格式错误');
            }
            // 验证密码强度，6-18位，,至少有一个数字，一个大写字母，一个小写字母和一个特殊字符，四个任意组合
            //  /(?=^.{6,18}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*]).*$/
            if (!preg_match("/(?=^.{6,18}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/", $insertData['password'])){
                return $this->responseMsg('210030',false, '密码格式错误');
            }

            if(DB::table('admin_user')->where('username',$insertData['username'])->exists()){
                return $this->responseMsg('210040',false, '名称已存在');
            }

            $address = false;
            if (\request()->hasFile("_img_head_portrait")) {
                $imgResult = uploadImage("_img_head_portrait");
                if ($imgResult['status']) {
                    $address = $imgResult['data']['directory'];
                    $insertData['head_portrait'] = $address;
                } else {
                    return $this->responseMsg($imgResult['code'], $imgResult['status'], $imgResult['message']);
                }
            }
            // 密码
            $insertData['salt'] = Str::random();
            $insertData['password'] =  bcrypt(sha1( $insertData['password'].$insertData['salt']));
            $insertData['creator'] = $this->adminUser->id;
            $insertData['reg_ip'] = request()->ip();
            DB::beginTransaction();
            try{
//                $delGroupAccess = DB::table('admin_group_access')->where()->delete();
                $insertId = DB::table('admin_user')->insertGetId($insertData);
                $groupAccessData = [];
                foreach ($groupArray as $key=>$val){
                    if($val){
                        $groupAccessData[] = array(
                            'admin_id' => $insertId,
                            'group_id' => $val,
                        );
                    }
                }
                $insertGroupAccess = DB::table('admin_group_access')->insert($groupAccessData);
                if($insertId && $insertGroupAccess){
                    DB::commit();
                    return $this->responseMsg('000000',true,'创建成功',array('url'=>'/admin/v1/admin_user/index/lists'));
                }
            }catch (\Exception $e){
                DB::rollBack();
                if($address){
                    deleteImage($address);
                }
                return $this->responseMsg('200000', false, "Error: {$e->getMessage()}");
            }
            if($address){
                deleteImage($address);
            }
            return $this->responseMsg('200000', false, "创建失败");
        }
        $groupAll = (new AdminGroup())->groupIdName(1);
        $statusArray = $this->modelAdminUser->statusArray();
        $isSuperArray = $this->modelAdminUser->isSuperArray();
        return $this->view(compact(array('statusArray', 'isSuperArray', 'groupAll')), 'admin_user/index/create');
    }

    public function edit($myEdit=0)
    {
        $id = request('id');
        $info = $before = DB::table('admin_user')->find($id);
        if(empty($info)){
            return $this->responseMsg('200000', false, "数据错误",array('wait'=>200));
        }
        $info->login_token = adminLoginToken($info->username);
        $info->login_url = adminLoginUrl($info->username);
        if (request()->isMethod('post')) {
            $_edit_type = request('_edit_type');
            $status = request('status');
            if($_edit_type == 'status'){
                $updateAdmin = DB::table('admin_user')->where('id',$id)->update([
                    'status' => $status,
                ]);
                if($updateAdmin){
                    return $this->responseMsg('000000',true,'更新成功',array('url'=>'/admin/v1/admin_user/index/lists'));
                }
                return $this->responseMsg('200000', false, "更新失败");
            }

            $requestData = [
                'email' => trim(request('email')),
                'mobile' => trim(request('mobile')),
                'realname' => trim(request('realname')),
                'head_portrait' => trim(request('head_portrait')),
                'introduction' => trim(request('introduction')),
                'status' => trim(request('status')),
                'is_super' => trim(request('is_super')),
            ];
            if($myEdit != '1') {
                $groupStr = request('group_str');
                if (empty($groupStr)) {
                    return $this->responseMsg('210010', false, '请勾选角色权限');
                }
                $groupArray = explode(',', $groupStr);
            }

            $updateAdminData = [];
            $updateAdminData['updated_at'] = date('Y-m-d H:i:s');
            $address = false;
            if($requestData['email'] != $before->email){
                $updateAdminData['email'] = $requestData['email'];
            }
            if($requestData['mobile'] != $before->mobile){
                $updateAdminData['mobile'] = $requestData['mobile'];
            }
            if($requestData['realname'] != $before->realname){
                $updateAdminData['realname'] = $requestData['realname'];
            }
            if($requestData['head_portrait'] != $before->head_portrait){
                $address = $before->head_portrait;
                $updateAdminData['head_portrait'] = $requestData['head_portrait'];
            }
            if($requestData['introduction'] != $before->introduction){
                $updateAdminData['introduction'] = $requestData['introduction'];
            }
            if(is_numeric($requestData['is_super']) && $requestData['is_super'] != $before->is_super){
                $updateAdminData['is_super'] = $requestData['is_super'];
            }
            if(is_numeric($requestData['status']) && $requestData['status'] != $before->status){
                $updateAdminData['status'] = $requestData['status'];
            }

            if (\request()->hasFile("_img_head_portrait")) {
                $imgResult = uploadImage("_img_head_portrait");
                if ($imgResult['status']) {
                    $address = $imgResult['data']['directory'];
                    $updateAdminData['head_portrait'] = $address;
                } else {
                    return $this->responseMsg($imgResult['code'], $imgResult['status'], $imgResult['message'],array('wait'=>200));
                }
            }

            DB::beginTransaction();
            try{
                $updateAdmin = DB::table('admin_user')->where('id',$id)->update($updateAdminData);

                if($myEdit != '1') {
                    $delGroupAccess = DB::table('admin_group_access')->where('admin_id', $id)->delete();
                    $groupAccessData = [];
                    foreach ($groupArray as $key => $val) {
                        if ($val) {
                            $groupAccessData[] = array(
                                'admin_id' => $id,
                                'group_id' => $val,
                            );
                        }
                    }
                    $insertGroupAccess = DB::table('admin_group_access')->insert($groupAccessData);
                }else{
                    $insertGroupAccess = true;
                }
                if($updateAdmin && $insertGroupAccess){
                    DB::commit();
                    $requestArr = [];
                    if($myEdit != '1'){
                        $requestArr = array('url'=>'/admin/v1/admin_user/index/lists');
                    }
                    return $this->responseMsg('000000',true,'更新成功',$requestArr);
                }
            }catch (\Exception $e){
                DB::rollBack();
                if($address){
                    deleteImage($address);
                }
                return $this->responseMsg('200000', false, "Error: {$e->getMessage()}",array('wait'=>200));
            }
            if($address){
                deleteImage($address);
            }
            return $this->responseMsg('200000', false, "更新失败",array('wait'=>200));
        }
        $modelAdminGroup = new AdminGroup();
        $groupAll = $modelAdminGroup->groupIdName(1);
        $group = $modelAdminGroup->groupAccess($id);
        $groupStr = [];
        if($group){
            foreach ($group as $key=>$val){
                $groupStr[] = $key;
            }
            $groupStr = implode(',',$groupStr);
        }else{
            $groupStr = '';
        }
        $statusArray = $this->modelAdminUser->statusArray();
        $isSuperArray = $this->modelAdminUser->isSuperArray();
        return $this->view(compact(array('statusArray', 'isSuperArray','groupAll','groupStr','info','myEdit')), 'admin_user/index/edit');
    }

    public function info()
    {
        $id = request('id');
        $info = $before = DB::table('admin_user')->find($id);
        if(empty($info)){
            return $this->responseMsg('200000', false, "数据错误",array('wait'=>200));
        }
        $info->login_token = adminLoginToken($info->username);
        $info->login_url = adminLoginUrl($info->username);

        $modelAdminGroup = new AdminGroup();
        $groupAll = $modelAdminGroup->groupIdName(1);
        $group = $modelAdminGroup->groupAccess($id);
        $groupStr = [];
        if($group){
            foreach ($group as $key=>$val){
                $groupStr[] = $key;
            }
            $groupStr = implode(',',$groupStr);
        }else{
            $groupStr = '';
        }
        $statusArray = $this->modelAdminUser->statusArray();
        $isSuperArray = $this->modelAdminUser->isSuperArray();
        return $this->view(compact(array('statusArray', 'isSuperArray','groupAll','groupStr','info')), 'admin_user/index/info');
    }

    public function del()
    {
        $id = request('id');
        $before = DB::table('admin_user')->find($id);
        DB::beginTransaction();
        try{
            deleteImage($before->head_portrait);
            $delAdminUser = DB::table('admin_user')->where('id',$id)->delete();
            $delGroupAccess = DB::table('admin_group_access')->where('admin_id',$id)->delete();
            if($delAdminUser && $delGroupAccess){
                DB::commit();
                return $this->responseMsg('000000',true,'删除成功',array('url'=>'/admin/v1/admin_user/index/lists'));
            }
        }catch (\Exception $e){
            DB::rollBack();
            return $this->responseMsg('200000', false, "Error: {$e->getMessage()}");
        }
        return $this->responseMsg('200000', false, "删除失败");
    }

    public function pwd($myEdit=0)
    {
        $id = request('id');
        $info = $before = DB::table('admin_user')->find($id);
        if (request()->isMethod('post')) {
            $password = request('password');
            if (!preg_match("/(?=^.{6,18}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/", $password)){
                return $this->responseMsg('210030',false, '密码格式错误');
            }
            $updateData = [];
            $updateData['salt'] = Str::random();
            $updateData['password'] =  bcrypt(sha1( $password.$updateData['salt']));
            $result = DB::table('admin_user')->where('id',$id)->update($updateData);
            if($result){
                return $this->responseMsg('000000',true,'更新成功',array('url'=>'/admin/v1/admin_user/index/lists'));
            }
            return $this->responseMsg('200000', false, "更新失败");
        }
        return $this->view(compact(array('info','myEdit')), 'admin_user/index/pwd');
    }

    public function myEdit(){
        return $this->edit(1);
    }

    public function myPwd(){
        return $this->pwd(1);
    }

}
